package com.googlecode.gwt4gae.client.menu;

import java.util.List;

import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.googlecode.gwt4gae.client.AppEvents;
import com.googlecode.gwt4gae.client.BaseAction;
import com.googlecode.gwt4gae.model.Menu;

public class MenuAction extends BaseAction {
	private final MenuServiceAsync menuService = GWT.create(MenuService.class);
	private MenuView view;

	public MenuAction() {
		registerEventTypes(AppEvents.HOME, AppEvents.SHOW_MENU, AppEvents.HIDE_PAGE, AppEvents.TAB_CHANGE);
	}

	@Override
	protected void initialize() {
		view = new MenuView(this);			
	}

	private MenuModel getMenuModel(List<Menu> menus) {		
		MenuModel treeModel = new MenuModel(menus.get(0).getId(), menus.get(0).getName(), menus.get(0).getCode(),menus.get(0).getUrl());
		MenuModel m11 = new MenuModel(11l, "m11", "m11","");
		MenuModel m12 = new MenuModel(12l, "m12", "m12","");
		MenuModel m13 = new MenuModel(13l, "m13", "m13","");
		treeModel.add(m11);
		MenuModel m111 = new MenuModel(111l, "m111", "m111","");
		m11.add(m111);
		treeModel.add(m12);
		treeModel.add(m13);
		return treeModel;
	}
	
	private void registAction(List<Menu> menus) {
		for (Menu menu : menus) {
			if (menu.getChildren() != null) {
				registAction(menu.getChildren());
			}
		}
	}

	@Override
	public void handleEvent(final AppEvent event) {	
		menuService.getMenus(new AsyncCallback<List<Menu>>() {
			public void onFailure(Throwable caught) {

			}
			public void onSuccess(List<Menu> result) {
				AppEvent ae = new AppEvent(event.getType(), getMenuModel(result));
				registAction(result);
				forwardToView(view, ae);
			}
		});
		
	}
}
